package km.TestAnimation;

import java.io.*;
import java.net.*;
import android.app.*;
import android.content.*;
import android.graphics.*;
import android.net.*;
import android.os.*;
import android.util.*;
import android.view.*;
import android.view.animation.*;
import android.webkit.*;
import android.widget.*;

/**
 * This sample application shows how to use layout animation and various
 * transformations on views. The result is a 3D transition between a
 * ListView and an ImageView. When the user clicks the list, it flips to
 * show the picture. When the user clicks the picture, it flips to show the
 * list. The animation is made of two smaller animations: the first half
 * rotates the list by 90 degrees on the Y axis and the second half rotates
 * the picture by 90 degrees on the Y axis. When the first half finishes, the
 * list is made invisible and the picture is set visible.
 */
public class TestAnimation extends Activity
 {
    private WebView vMain;
    private WebView mContainer;
    private WebView vDetail;
	private String mainUrl;
	private boolean isInit;
    Activity activity;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        
//         mContainer = new LinearLayout(this);
//        setContentView(mContainer);
//        vMain = new WebView(this);
//        vMain.loadUrl("http://google.co.kr");
//        vDetail = new WebView(this);
//        vDetail.loadUrl("http://m.naver.com");
//        mContainer.addView(vMain);
//        mContainer.addView(vDetail);
//        getWindow().requestFeature(Window.FEATURE_PROGRESS);
        requestWindowFeature(Window.FEATURE_PROGRESS);
        
        setContentView(R.layout.main);
        activity = this;
//        initWebView("http://m.naver.com");
//        mainUrl = "http://webprogrammer.tistory.com/69";
        mainUrl = "http://google.co.kr";
//        mainUrl = "http://203.236.20.167/work/s.jsp";
//        mainUrl = "http://172.20.49.123:8080/Test/sw/index.html";
//        mainUrl = "http://172.20.49.123:8080/DevOnOffice/";
        initWebView(mainUrl);
      
//        vMain.setOnClickListener(new OnClickListener() {
//			
//			public void onClick(View v) {
//				Log.e("", "onclick===>>");
//			        applyRotation(1, 0, 90);			
//			}
//		});

        // Prepare the ImageView
//        vDetail.setClickable(true);
//        vDetail.setFocusable(true);
//        vDetail.setOnTouchListener(new OnTouchListener() {
//			
//			public boolean onTouch(View v, MotionEvent event) {
//				Log.e("", "ontouch===>>");
//		        applyRotation(-1, 360, 90);		
//				return false;
//			}
//		});
//        vDetail.setOnClickListener(new OnClickListener() {
//            public void onClick(View v) {
//                applyRotation(-1, 180, 90);
//            }
//          });

        // Since we are caching large views, we want to keep their cache
        // between each animation
//        mContainer.setPersistentDrawingCache(ViewGroup.PERSISTENT_ANIMATION_CACHE);
    }

    public void initWebView(String url){ 
        Log.d("","initWebView():");    
        isInit = true;
        mContainer = (WebView) findViewById(R.id.webview);
        mContainer.getSettings().setJavaScriptEnabled(true);
        mContainer.loadUrl(url);
        mContainer.setWebViewClient(new TestWebViewClient());
        mContainer.setWebChromeClient(new TestWebChromeClient()); 
        mContainer.setPersistentDrawingCache(ViewGroup.PERSISTENT_ANIMATION_CACHE);
//        mContainer.setOnTouchListener(new OnTouchListener() {
//			
//			public boolean onTouch(View v, MotionEvent event) {
//				Log.e("", "ontouch===>>");
//		        applyRotation(1, 0, 90);		
//				return false;
//			}
//		});
    }    
    /**
     * Setup a new 3D rotation on the container view.
     *
     * @param position the item that was clicked to show a picture, or -1 to show the list
     * @param start the start angle at which the rotation must begin
     * @param end the end angle of the rotation
     */
    private void applyRotation(int position, float start, float end) {
        // Find the center of the container
        final float centerX = mContainer.getWidth() / 2.0f;
        final float centerY = mContainer.getHeight() / 2.0f;

        // Create a new 3D rotation with the supplied parameter
        // The animation listener is used to trigger the next animation
        final Rotate3dAnimation rotation =
                new Rotate3dAnimation(start, end, centerX, centerY, 310.0f, true);
        rotation.setDuration(500);
        rotation.setFillAfter(true);
        rotation.setInterpolator(new AccelerateInterpolator());
        rotation.setAnimationListener(new DisplayNextView(position));

        mContainer.startAnimation(rotation);
    }

    /**
     * This class listens for the end of the first half of the animation.
     * It then posts a new action that effectively swaps the views when the container
     * is rotated 90 degrees and thus invisible.
     */
    private final class DisplayNextView implements Animation.AnimationListener {
        private final int mPosition;

        private DisplayNextView(int position) {
            mPosition = position;
        }

        public void onAnimationStart(Animation animation) {
        }

        public void onAnimationEnd(Animation animation) {
            mContainer.post(new SwapViews(mPosition));
        }

        public void onAnimationRepeat(Animation animation) {
        }
    }

    /**
     * This class is responsible for swapping the views and start the second
     * half of the animation.
     */
    private final class SwapViews implements Runnable {
        private final int mPosition;

        public SwapViews(int position) {
            mPosition = position;
        }

        public void run() {
            final float centerX = mContainer.getWidth() / 2.0f;
            final float centerY = mContainer.getHeight() / 2.0f;
            Rotate3dAnimation rotation;
            
            if (mPosition > -1) {
//                vMain.setVisibility(View.GONE);
//                vDetail.setVisibility(View.VISIBLE);
//                vDetail.requestFocus();

                rotation = new Rotate3dAnimation(90, 0, centerX, centerY, 0.0f, false);
            } else {
//                vDetail.setVisibility(View.GONE);
//                vMain.setVisibility(View.VISIBLE);
//                vMain.requestFocus();

                rotation = new Rotate3dAnimation(90, 0, centerX, centerY, 310.0f, true);
            }

            rotation.setDuration(500);
            rotation.setFillAfter(true);
            rotation.setInterpolator(new DecelerateInterpolator());

            mContainer.startAnimation(rotation);
        }
    }
    private class TestWebChromeClient extends WebChromeClient {
      public void onProgressChanged(WebView view, int progress) {
          activity.setProgress(progress * 100);
      } 
           @Override
          public boolean onJsAlert(WebView view, String url, String message,
                  JsResult result){
                   Log.e("Alert", ">> url :"+ url );
                   Log.e("Alert", ">> msg :"+ message);
                   result.confirm();
                   return false;
          }
           @Override
          public boolean onJsConfirm(WebView view, String url, String message,
                          JsResult result){
                       Log.e("JsConfirm", ">> url :"+ url );
                       Log.e("JsConfirm", ">> msg :"+ message);                
                      return super.onJsConfirm(view, url, message, result);
                  }
  }   
    private class TestWebViewClient extends WebViewClient {
        public void onReceivedError(WebView view, int errorCode, String description, String fallingUrl) {
            Toast.makeText(activity, "로딩오류"+description, Toast.LENGTH_SHORT).show();
        }
       @Override
       public boolean shouldOverrideUrlLoading(WebView view, String url){
    	   Log.d("HelloWebViewClient","#### UrlLoading()  :: "+url);

	//    	   if(!url.contains("images"))
    	       if(url.endsWith(".apk"))
    	           downloadFile(url);
    	       else{
    	    	   view.clearView();
    	           view.loadUrl(url);
    	       }
           return true;
       }
     
       @Override
       public void onPageFinished(WebView view, String url){
           Log.d("HelloWebViewClient","#### onPageFinished()  ");
//           applyRotation(1, 0, 90);
       }
       @Override
    	public void onPageStarted(WebView view, String url, Bitmap favicon) {
    	   Log.d("HelloWebViewClient","#### onPageStarted()  ");
    	   if(isInit){
    		   isInit = false;
    	   }else{
    	    applyRotation(1, 0, 90);
    	   }
    		super.onPageStarted(view, url, favicon);
    	}

//       public boolean shouldOverrideKeyEvent (WebView view, KeyEvent event) {
//           int keyCode = event.getKeyCode();
//           Log.d("HelloWebViewClient","#### shouldOverrideKeyEvent()  " + keyCode);  
//           if ((keyCode == KeyEvent.KEYCODE_DPAD_LEFT) && mContainer.canGoBack()) {
//        	   mContainer.goBack();
//               return true;
//           }else if ((keyCode == KeyEvent.KEYCODE_DPAD_RIGHT) && mContainer.canGoForward()) {
//        	   mContainer.goForward();
//               return true;
//           }       
//           return false;
//      } 
    }
    private void downloadFile(String fileUrl){
        URL myFileUrl =null;          
        try {
             myFileUrl= new URL(fileUrl);
        } catch (MalformedURLException e) {
             e.printStackTrace();
        }
        try {
             HttpURLConnection conn= (HttpURLConnection)myFileUrl.openConnection();
             conn.setDoInput(true);
             conn.connect();
             InputStream is = conn.getInputStream();


      // 다운 받는 파일의 경로는 sdcard/ 아래 이다. 단, sdcard에 접근하려면 uses-permission에 android.permission.WRITE_EXTERNAL_STORAGE을 추가해야한다.
             String mPath = "sdcard/download/downTest.apk";
             FileOutputStream fos;
             File f = new File(mPath);
             if ( f.createNewFile() ) {
                fos = new FileOutputStream(mPath);   
                int read;
                while ( (read =  is.read()) != -1) {
                fos.write(read);
                }
                fos.close();
                Toast.makeText(getApplicationContext(), "download complete", 0).show();
                // 안드로이드 패키지 매니저를 통해 다운 받은 apk 파일을 처리하도록 한다.
                Log.e("MEDIA_SHARED", ">> : "+Environment.MEDIA_SHARED);
                Log.e("StorageDirectory", ">> : "+Environment.getExternalStorageDirectory());
                Log.e("DownloadCacheDirectory", ">> : "+Environment.getDownloadCacheDirectory());
                File apkFile = new File(Environment.getExternalStorageDirectory()+ "/download/downTest.apk");
                Intent intent = new Intent(Intent.ACTION_VIEW);
                intent.setDataAndType( Uri.fromFile(apkFile), "application/vnd.android.package-archive");
                startActivity(intent);
             }else{
                 f.delete();
                 Toast.makeText(getApplicationContext(), "already download file", 0).show();
             }
        } catch (IOException e) {
             e.printStackTrace();
        }
   }

    private void launchActivityOutApk() {
        
        Intent intent = new Intent("android.lgt.mofileviewer.intent.action.OPEN_FILE");
        
        intent.putExtra("app", "MBOFFICE");
        intent.putExtra("docid", "test.account%2Fmailbox%2F0001%2Fattach.conv%2F0000D7B29666");
        intent.putExtra("EMS_CMD", "mailattachview");
        intent.putExtra("Device-Info", "Eclipse");
        intent.putExtra("CompanyID", "company");
        intent.putExtra("DOMAIN", "lgcns.co.kr");
        intent.putExtra("serveraddr", "172.20.49.104");
        intent.putExtra("serverport", "8080");
        
        startActivity(intent);
    }       
        
    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
	    menu.add(0,0,0,"<<");
	    menu.add(0,1,1,">>");
	    menu.add(0,2,2,"FileViewer");
    	return super.onCreateOptionsMenu(menu);
    }
    @Override
    public boolean onMenuItemSelected(int featureId, MenuItem item) {
    	if(item.getOrder() == 0 && mContainer.canGoBack())
    		 mContainer.goBack();
    	else if(item.getOrder() == 1 && mContainer.canGoForward())
   		 	 mContainer.goForward();
    	else
    	    launchActivityOutApk();
    	return super.onMenuItemSelected(featureId, item);
    }
}
